import { Controller, Post, Inject, Provide } from '@midwayjs/decorator'
import { Context } from 'egg'

import { BaseController } from './base'
import { TemplateService } from '../service/template'
import { UploadService } from '../service/upload'
import { CODE } from '../constants/code'
import { getBookmarks } from '../utils/docx-editor'

const _ = require('lodash')

@Provide()
@Controller('/api/system/template')
export class TemplateController extends BaseController {

  @Inject()
  ctx: Context

  @Inject()
  templateService: TemplateService

  @Inject()
  uploadService: UploadService

  @Post('/')
  async add() {
    const { id, is_system_user } = this.ctx.state

    if (!id || !is_system_user) {
      return this.notOk(CODE.NOT_ALLOWED)
    }

    const stream = await this.ctx.getFileStream()
    const upload = await this.uploadService.upload(stream)

    if (upload?.id) {
      const buffer = await this.uploadService.getBuffer(upload.id)
      const bookmarks = await getBookmarks(buffer)

      const addedTemplate = await this.templateService.add({
        attachment_id: upload.id,
        create_by_id: id,
        bookmarks: _.uniq(bookmarks)
      })

      if (addedTemplate) {
        return this.ok(addedTemplate)
      }
    }

    return this.notOk(CODE.FAIL)
  }
}